package com.example.myproject.service;

import com.example.myproject.mapper.UserMapper;
import com.example.myproject.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityNotFoundException;
import java.util.UUID;

@Service
public class PasskeyService {

    @Autowired
    private UserMapper userMapper;

    // 注册时生成 Passkey
    @Transactional
    public String generatePasskeyForNewUser(User user) {
        String passkey = generateSecurePasskey();
        user.setPasskey(passkey);
        userMapper.insert(user); // 改为使用 MyBatis-Plus 插入
        return passkey;
    }

    // Passkey 刷新
    @Transactional
    public String refreshPasskey(Long userId) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new EntityNotFoundException("用户不存在");
        }
        String newPasskey = generateSecurePasskey();
        user.setPasskey(newPasskey);
        userMapper.updateById(user); // ✅ 记得更新数据库
        return newPasskey;
    }

    // 生成安全的 Passkey
    private String generateSecurePasskey() {
        return UUID.randomUUID().toString().replace("-", "");
    }
}
